package com.blue.firecat.serivce.impl;

import com.blue.firecat.contants.Contants;
import com.blue.firecat.contants.Result;
import com.blue.firecat.dao.NoteDao;
import com.blue.firecat.dao.OrderDao;
import com.blue.firecat.dao.TradeDao;
import com.blue.firecat.dao.UserDao;
import com.blue.firecat.entity.*;
import com.blue.firecat.enums.ErrorEnum;
import com.blue.firecat.enums.OrderTypeEnum;
import com.blue.firecat.enums.TradeStatusEnum;
import com.blue.firecat.enums.UserTypeEnum;
import com.blue.firecat.exception.ServiceException;
import com.blue.firecat.serivce.TradeService;
import com.blue.firecat.utils.email.EmailUtils;
import com.blue.firecat.utils.mapper.BeanMapper;
import com.blue.firecat.vo.TradeVo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;


/**
 * @描述
 * @时间 2017/6/22 23:00
 * @作者 肖亦鸣
 */
@Service
public class TradeServiceImpl implements TradeService {
    @Autowired
    TradeDao tradeDao;
    @Autowired
    OrderDao orderDao;
    @Autowired
    UserDao userDao;

    @Override
    public int deleteByExample(TradeExample example) {
        return tradeDao.deleteByExample(example);
    }

    @Override
    public Result<Trade> deleteByPrimaryKey(Long id) {
        Result<Trade> result = new Result<>();
        //查询交易
        Trade trade = tradeDao.selectByPrimaryKey(id);
        if (trade == null) {
            result.setCode(ErrorEnum.TRADE_NOT_FOUND);
            return result;
        }
        //如果是审核中就可以撤销
        if (trade.getStatus().equals(TradeStatusEnum.REVIEW.getCode())
                || trade.getStatus().equals(TradeStatusEnum.ABNORMAL_ORDERS.getCode())
                || trade.getStatus().equals(TradeStatusEnum.NOT_PASS.getCode())
                || trade.getStatus().equals(TradeStatusEnum.CHECK_NOT_PASS.getCode())) {
            int i = tradeDao.deleteByPrimaryKey(id);
            if (i == 0) {
                result.setCode(ErrorEnum.TRADE_DELETE_ERROR);
            }
        } else {
            result.setCode(ErrorEnum.TRADE_STATUS_ERROR);
        }
        return result;
    }

    @Override
    @Transactional
    public Result<Trade> insertSelective(User user, Trade trade) {
        Result<Trade> result = new Result<>();
        Order order = orderDao.selectByPrimaryKey(trade.getOrderId());
        //订单异常
        if (order == null) {
            result.setCode(ErrorEnum.ORDER_DOES_NOT_EXIST);
            return result;
        }
        if (!order.getType().equals(OrderTypeEnum.WAITING.getCode())) {
            result.setCode(ErrorEnum.ORDER_IS_NOT_WAITING);
            return result;
        }
        //查询交易,看看这个人有没有审核
        TradeExample example = new TradeExample();
        example.getOredCriteria().add(example.createCriteria().andOrderIdEqualTo(trade.getOrderId()).andUserIdEqualTo(user.getId()));
        List<Trade> trades = tradeDao.selectByExample(example);
        if (CollectionUtils.isNotEmpty(trades)) {
            result.setCode(ErrorEnum.ORDER_HAVEING_APPLIED);
            return result;
        }
        //订单正常,交易下单
        BeanMapper.copy(order, trade);
        trade.setId(null);
        trade.setUserId2(order.getUserId());//客服id
        trade.setUpdateTime(new Date());
        trade.setUserId(user.getId());//打手id
        trade.setUserName(user.getName());
        if (trade.getStatus() == null) {
            trade.setStatus(TradeStatusEnum.IS_WORK.getCode());
        }
        //都没问题,插入数据库
        int i = tradeDao.insertSelective(trade);
        if (i == 0) {
            result.setCode(ErrorEnum.TRADE_CREATE_FAIL);
        }
        //后期更改,打手申请之后可以直接看到账号密码了,不用管理员审核
        order.setType(OrderTypeEnum.IS_WORK.getCode());
        order.setOperate(user.getName());
        orderDao.updateByPrimaryKeySelective(order);
        result.setData(trade);
        return result;
    }

    @Override
    public Result<List<Trade>> selectByExample(TradeVo tradeVo, User user) {
        Result result = new Result();
        TradeExample example = new TradeExample();

        //查询交易,管理员和客服可以查询所有,打手只能看自己的
        //如果是打手
        if (user.getType().equals(UserTypeEnum.BEATER.getCode())) {
            example.getOredCriteria().add(example.createCriteria()
                    .andGameIdEqualTo(tradeVo.getGameId())
                    .andIdEqualTo(tradeVo.getTradeId())
                    .andOrderIdEqualTo(tradeVo.getOrderId())
                    .andUserIdEqualTo(user.getId())
                    .andStatusEqualTo(tradeVo.getTradeStatus())
                    .andCreateTimeBetween(tradeVo.getDateMin(), tradeVo.getDateMax()));
        } else {
            example.getOredCriteria().add(example.createCriteria()
                    .andGameIdEqualTo(tradeVo.getGameId())
                    .andIdEqualTo(tradeVo.getTradeId())
                    .andOrderIdEqualTo(tradeVo.getOrderId())
                    .andStatusEqualTo(tradeVo.getTradeStatus())
                    .andCreateTimeBetween(tradeVo.getDateMin(), tradeVo.getDateMax()));
        }

        List<Trade> trades = tradeDao.selectByExample(example);
        if (CollectionUtils.isEmpty(trades)) {
            result.setCode(ErrorEnum.TRADE_NOT_FOUND);
            return result;
        }
        for (Trade trade : trades) {
            Note note = noteDao.selectByPrimaryKey(trade.getOrderId());
            if (note != null) {
                trade.setNote(note.getNote());
            }
        }
        //如果是用户,并且是,未知,待审核,审核不通过,已结算状态
        this.clearTrade(user, trades);

        result.setData(trades);
        return result;
    }

    private void clearTrade(User user, List<Trade> trades) {
        if (Contants.isBeater(user)) {
            for (Trade trade : trades) {
                if (trade.getStatus().equals(TradeStatusEnum.UNKNOWN.getCode())
                        || trade.getStatus().equals(TradeStatusEnum.REVIEW.getCode())
                        || trade.getStatus().equals(TradeStatusEnum.HAS_BEEN_SETTLED.getCode())
                        || trade.getStatus().equals(TradeStatusEnum.NOT_PASS.getCode())) {
                    trade.setGameUser("*********");
                    trade.setGameUserName("*********");
                    trade.setGameUserChild("*********");
                    trade.setGamePassword("*********");
                    trade.setPhone(null);
                }
            }
        }
    }

    @Autowired
    NoteDao noteDao;

    @Override
    public Result<Trade> selectByPrimaryKey(Long id, User user) {
        Result<Trade> result = new Result<>();
        Trade trade = tradeDao.selectByPrimaryKey(id);
        if (trade == null) {
            result.setCode(ErrorEnum.TRADE_NOT_FOUND);
            return result;
        }
        Note note = noteDao.selectByPrimaryKey(trade.getOrderId());
        if (note != null) {
            trade.setNote(note.getNote());
        }
        //如果是用户,并且是,未知,待审核,审核不通过,已结算状态
        this.clearTrade(user, Collections.singletonList(trade));
        result.setData(trade);
        return result;
    }

    @Override
    @Transactional
    public Result<Trade> updateByPrimaryKeySelective(TradeVo tradeVo, User user) {

        return null;
    }

    /**
     * 设置审核通过代练中
     *
     * @param tradeVo
     * @param user
     * @return
     */
    @Override
    public Result<Trade> setTradeWork(TradeVo tradeVo, User user) {
        Result<Trade> result = new Result<>();
        if (Contants.verifyAuthority(user, result)) return result;
        //查询交易
        Trade trade = tradeDao.selectByPrimaryKey(tradeVo.getTradeId());
        if (trade == null) {
            result.setCode(ErrorEnum.TRADE_NOT_FOUND);
            return result;
        }
        if (trade.getStatus().equals(TradeStatusEnum.REVIEW.getCode())
                || trade.getStatus().equals(TradeStatusEnum.NOT_PASS.getCode())) {
            //把其他交易变成不通过
            Trade tradeNotPass = new Trade();
            tradeNotPass.setStatus(TradeStatusEnum.NOT_PASS.getCode());
            tradeNotPass.setOrderId(trade.getOrderId());
            tradeDao.updateByPrimaryKey(tradeNotPass);
            //更新交易 更新成已通过
            trade.setStatus(TradeStatusEnum.IS_WORK.getCode());
            trade.setUpdateTime(new Date());
            trade.setOperate(user.getName());
            int i = tradeDao.updateByPrimaryKeySelective(trade);
            if (i == 0) {
                result.setCode(ErrorEnum.TRADE_AUDIT_ERROE);
                return result;
            }
            //更新订单
            Order order = new Order();
            order.setId(trade.getOrderId());
            order.setType(OrderTypeEnum.IS_WORK.getCode());
            order.setOperate(user.getName());
            int i1 = orderDao.updateByPrimaryKeySelective(order);
            if (i1 == 0) {
                result.setCode(ErrorEnum.ORDER_MODIFICATION_STATUS_ERROR);
                throw new ServiceException(ErrorEnum.ORDER_MODIFICATION_STATUS_ERROR);
            }
        } else {
            result.setCode(ErrorEnum.TRADE_STATUS_ERROR);
            return result;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EmailUtils emailUtils = new EmailUtils("", userDao.selectByPrimaryKey(trade.getUserId()).getEmail(), trade.getOrderId().toString());
                    emailUtils.send(3);
                } finally {
                }
            }
        }).start();
        return result;
    }

    /**
     * 设置审核不通过
     *
     * @param tradeVo
     * @param user
     * @return
     */
    @Override
    public Result<Trade> setTradeNotPass(TradeVo tradeVo, User user) {
        Result<Trade> result = new Result<>();
        if (Contants.verifyAuthority(user, result)) return result;

        //查询交易
        Trade trade = tradeDao.selectByPrimaryKey(tradeVo.getTradeId());
        if (trade == null) {
            result.setCode(ErrorEnum.TRADE_NOT_FOUND);
            return result;
        }
        if (trade.getStatus().equals(TradeStatusEnum.REVIEW.getCode())
                || trade.getStatus().equals(TradeStatusEnum.NOT_PASS.getCode())) {
            //更新交易
            trade.setStatus(TradeStatusEnum.NOT_PASS.getCode());
            trade.setUpdateTime(new Date());
            trade.setOperate(user.getName());
            int i = tradeDao.updateByPrimaryKeySelective(trade);
            if (i == 0) {
                result.setCode(ErrorEnum.TRADE_AUDIT_ERROE);
                return result;
            }
            return result;
        } else {
            result.setCode(ErrorEnum.TRADE_STATUS_ERROR);
            return result;
        }
    }

    /**
     * 验收通过 -- 订单要变成待结算
     *
     * @param tradeVo
     * @param user
     * @return
     */
    @Override
    public Result<Trade> checkThrough(TradeVo tradeVo, User user) {
        Result<Trade> result = new Result<>();
        if (Contants.verifyAuthorityOrCustom(user, result)) return result;
        //查询交易
        Trade trade = tradeDao.selectByPrimaryKey(tradeVo.getTradeId());
        if (trade == null) {
            result.setCode(ErrorEnum.TRADE_NOT_FOUND);
            return result;
        }
        //是待验收的才更新,或者验收不通过
        if (trade.getStatus().equals(TradeStatusEnum.TO_BE_ACCEPTED.getCode())
                || trade.getStatus().equals(TradeStatusEnum.CHECK_NOT_PASS.getCode())) {
            //更新交易 - 待结算
            trade.setStatus(TradeStatusEnum.TO_BE_SETTLED.getCode());
            trade.setOperate(user.getName());
            trade.setUpdateTime(new Date());
            int i = tradeDao.updateByPrimaryKey(trade);
            if (i == 0) {
                result.setCode(ErrorEnum.TRADE_MODIFIED_STATUS_ERROR);
                return result;
            }
            //更新订单 - 待结算
            Order order = new Order();
            order.setId(trade.getOrderId());
            order.setType(OrderTypeEnum.TO_BE_SETTLED.getCode());
            order.setOperate(user.getName());
            int i1 = orderDao.updateByPrimaryKeySelective(order);
            if (i1 == 0) {
                result.setCode(ErrorEnum.ORDER_MODIFICATION_STATUS_ERROR);
                throw new ServiceException(ErrorEnum.ORDER_MODIFICATION_STATUS_ERROR);
            }
        } else {
            result.setCode(ErrorEnum.TRADE_STATUS_ERROR);
            return result;
        }
        return result;
    }

    /**
     * 打手打完了,验收不通过
     *
     * @param tradeVo
     * @return
     */
    @Override
    public Result<Trade> setTradeCheckToNotPass(TradeVo tradeVo, User user) {
        Result<Trade> result = new Result<>();
        if (Contants.verifyAuthority(user, result)) return result;

        //查询交易
        Trade trade = tradeDao.selectByPrimaryKey(tradeVo.getTradeId());
        if (trade == null) {
            result.setCode(ErrorEnum.TRADE_NOT_FOUND);
            return result;
        }
        if (trade.getStatus().equals(TradeStatusEnum.TO_BE_ACCEPTED.getCode())) {
            //更新交易 -- 验收不通过
            trade.setStatus(TradeStatusEnum.CHECK_NOT_PASS.getCode());
            trade.setUpdateTime(new Date());
            trade.setOperate(user.getName());
            int i = tradeDao.updateByPrimaryKeySelective(trade);
            if (i == 0) {
                result.setCode(ErrorEnum.TRADE_AUDIT_ERROE);
                return result;
            }
            //更新订单 - 待结算
            Order order = new Order();
            order.setId(trade.getOrderId());
            order.setType(OrderTypeEnum.ABNORMAL_ORDERS.getCode());
            order.setOperate(user.getName());
            int i1 = orderDao.updateByPrimaryKeySelective(order);
            if (i1 == 0) {
                result.setCode(ErrorEnum.ORDER_MODIFICATION_STATUS_ERROR);
                throw new ServiceException(ErrorEnum.ORDER_MODIFICATION_STATUS_ERROR);
            }
            return result;
        } else {
            result.setCode(ErrorEnum.TRADE_STATUS_ERROR);
            return result;
        }
    }

    /**
     * 交易结算--订单也要变成已结算
     *
     * @param tradeVo
     * @param user
     * @return
     */
    @Override
    public Result<Trade> settlerTrade(TradeVo tradeVo, User user) {
        Result<Trade> result = new Result<>();
        if (Contants.verifyAuthority(user, result)) return result;
        //查询交易
        Trade trade = tradeDao.selectByPrimaryKey(tradeVo.getTradeId());
        if (trade == null) {
            result.setCode(ErrorEnum.TRADE_NOT_FOUND);
            return result;
        }

        //是待结算的才更新
        if (trade.getStatus().equals(TradeStatusEnum.TO_BE_SETTLED.getCode())) {
            //更新交易 -- 已结算
            trade.setStatus(TradeStatusEnum.HAS_BEEN_SETTLED.getCode());
            trade.setOperate(user.getName());
            trade.setUpdateTime(new Date());
            int i = tradeDao.updateByPrimaryKey(trade);
            if (i == 0) {
                result.setCode(ErrorEnum.TRADE_MODIFIED_STATUS_ERROR);
                return result;
            }
            //更新订单 -- 已结算
            Order order = new Order();
            order.setId(trade.getOrderId());
            order.setType(OrderTypeEnum.HAS_BEEN_SETTLED.getCode());
            order.setOperate(user.getName());
            int i1 = orderDao.updateByPrimaryKeySelective(order);
            if (i1 == 0) {
                result.setCode(ErrorEnum.ORDER_MODIFICATION_STATUS_ERROR);
                throw new ServiceException(ErrorEnum.ORDER_MODIFICATION_STATUS_ERROR);
            }
        } else {
            result.setCode(ErrorEnum.TRADE_STATUS_ERROR);
            return result;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EmailUtils emailUtils = new EmailUtils("", userDao.selectByPrimaryKey(trade.getUserId()).getEmail(), trade.getSettlePrice().toString());
                    emailUtils.send(1);
                } finally {
                }
            }
        }).start();
        return result;
    }

    @Override
    public Result<Trade> settlerTradeAll(TradeVo tradeVo, User user) {
        Result<Trade> result = new Result<>();
        if (Contants.verifyAuthority(user, result)) return result;
        String[] tradeIds = tradeVo.getTradeIds().split(",");
        for (String tradeId : tradeIds) {
            //查询交易
            Trade trade = tradeDao.selectByPrimaryKey(Long.valueOf(tradeId));
            if (trade == null) {
                result.setCode(ErrorEnum.TRADE_NOT_FOUND);
                return result;
            }
            //是待结算的才更新
            if (trade.getStatus().equals(TradeStatusEnum.TO_BE_SETTLED.getCode())) {
                //更新交易 -- 已结算
                trade.setStatus(TradeStatusEnum.HAS_BEEN_SETTLED.getCode());
                trade.setOperate(user.getName());
                trade.setUpdateTime(new Date());
                tradeDao.updateByPrimaryKey(trade);
                //更新订单 -- 已结算
                Order order = new Order();
                order.setId(trade.getOrderId());
                order.setType(OrderTypeEnum.HAS_BEEN_SETTLED.getCode());
                order.setOperate(user.getName());
                orderDao.updateByPrimaryKeySelective(order);
            } else {
                result.setCode(ErrorEnum.TRADE_STATUS_ERROR);
                return result;
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        EmailUtils emailUtils = new EmailUtils("", userDao.selectByPrimaryKey(trade.getUserId()).getEmail(), trade.getSettlePrice().toString());
                        emailUtils.send(1);
                    } finally {
                    }
                }
            }).start();
        }
        return result;
    }

    @Override
    public synchronized Result addPics(String fileNameNew, TradeVo tradeVo, User user) {
        Result result = new Result();
        Trade trade = tradeDao.selectByPrimaryKey(tradeVo.getTradeId());
        if (trade == null) {
            result.setCode(ErrorEnum.TRADE_NOT_FOUND);
            return result;
        }
        String pics = trade.getPhoto();
        //如果是空,就变成 ""
        if (StringUtils.isEmpty(pics)) {
            pics = "";
        } else {
            //否则 把新的文件名拼接起来
            fileNameNew = pics + Contants.PIC_CUTTING + fileNameNew;
        }
        if (pics.split(Contants.PIC_CUTTING).length >= Contants.PIC_MAX_NUM) {
            result.setCode(ErrorEnum.PIC_NUM_MUCH);
            return result;
        }
        //代练中,或者 异常单 ,或者 验证不通过
        if (trade.getStatus().equals(TradeStatusEnum.IS_WORK.getCode())
                || trade.getStatus().equals(TradeStatusEnum.ABNORMAL_ORDERS.getCode())
                || trade.getStatus().equals(TradeStatusEnum.CHECK_NOT_PASS.getCode())
                || trade.getStatus().equals(TradeStatusEnum.TO_BE_ACCEPTED.getCode())) {
            //把交易变成待验收
            trade.setOperate(user.getUserName());
            trade.setPhoto(fileNameNew);
            trade.setStatus(TradeStatusEnum.TO_BE_ACCEPTED.getCode());
            trade.setUpdateTime(new Date());
            tradeDao.updateByPrimaryKeySelective(trade);
            //把订单变成待验收
            Order order = new Order();
            order.setId(trade.getOrderId());
            order.setOperate(user.getUserName());
            order.setType(OrderTypeEnum.TO_BE_ACCEPTED.getCode());
            orderDao.updateByPrimaryKeySelective(order);
        } else {
            result.setCode(ErrorEnum.TRADE_STATUS_ERROR);
            return result;
        }
        return result;
    }

    /**
     * 交易,订单异常(比如:登陆不上)
     *
     * @param tradeVo
     * @param user
     * @return
     */
    @Override
    public Result<Trade> tradeCommitError(TradeVo tradeVo, User user) {
        Result<Trade> result = new Result<>();
        //查询交易
        Trade trade = tradeDao.selectByPrimaryKey(tradeVo.getTradeId());
        if (trade == null) {
            result.setCode(ErrorEnum.TRADE_NOT_FOUND);
            return result;
        }

        //是代练中的提交异常
        if (trade.getStatus().equals(TradeStatusEnum.IS_WORK.getCode())) {
            //更新交易 -- 异常单
            trade.setStatus(TradeStatusEnum.ABNORMAL_ORDERS.getCode());
            trade.setRemark(tradeVo.getRemark());
            trade.setOperate(user.getName());
            trade.setUpdateTime(new Date());
            int i = tradeDao.updateByPrimaryKey(trade);
            if (i == 0) {
                result.setCode(ErrorEnum.TRADE_MODIFIED_STATUS_ERROR);
                return result;
            }
            //更新订单 -- 异常单
            Order order = new Order();
            order.setId(trade.getOrderId());
            order.setType(OrderTypeEnum.ABNORMAL_ORDERS.getCode());
            order.setOperate(user.getName());
            int i1 = orderDao.updateByPrimaryKeySelective(order);
            if (i1 == 0) {
                result.setCode(ErrorEnum.ORDER_MODIFICATION_STATUS_ERROR);
                throw new ServiceException(ErrorEnum.ORDER_MODIFICATION_STATUS_ERROR);
            }
        } else {
            result.setCode(ErrorEnum.TRADE_STATUS_ERROR);
            return result;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EmailUtils emailUtils = new EmailUtils("", userDao.selectByPrimaryKey(trade.getUserId2()).getEmail(), trade.getOrderId().toString() + ",异常信息为:" + tradeVo.getRemark());
                    emailUtils.send(2);
                } finally {
                }
            }
        }).start();
        return result;
    }

    /**
     * 是否同意
     *
     * @param user
     * @param tradeVo
     * @return
     */
    @Override
    @Transactional
    public Result<Trade> tradeAgree(User user, TradeVo tradeVo) {
        Result result = new Result();
        Trade trade = new Trade();
        Trade selectByPrimaryKey = tradeDao.selectByPrimaryKey(tradeVo.getTradeId());
        if (selectByPrimaryKey == null) {
            result.setCode(ErrorEnum.ORDER_DOES_NOT_EXIST);
            return result;
        }
        if (selectByPrimaryKey.getStatus().equals(TradeStatusEnum.APPOINT_BEATER.getCode())) {
            //同意
            if (tradeVo.getAgree() == 1) {
                //交易变成代练中
                trade.setId(tradeVo.getTradeId());
                trade.setStatus(TradeStatusEnum.IS_WORK.getCode());
                trade.setUpdateTime(new Date());
                tradeDao.updateByPrimaryKeySelective(trade);
                //订单变成代练中
                Order order = new Order();
                order.setId(selectByPrimaryKey.getOrderId());
                order.setType(OrderTypeEnum.IS_WORK.getCode());
                order.setOperate(user.getName());
                orderDao.updateByPrimaryKeySelective(order);
            } else {
                //交易删除记录
                trade.setId(tradeVo.getTradeId());
                tradeDao.deleteByPrimaryKey(tradeVo.getTradeId());
                //订单变成待接手
                Order order = new Order();
                order.setId(selectByPrimaryKey.getOrderId());
                order.setType(OrderTypeEnum.WAITING.getCode());
                order.setOperate(user.getName());
                orderDao.updateByPrimaryKeySelective(order);
            }
        } else {
            result.setCode(ErrorEnum.TRADE_STATUS_ERROR);
        }

        return result;
    }

    @Override
    public Result<List<Trade>> tradeCount(TradeVo tradeVo, User user) {
        Result result = new Result();
        if (Contants.verifyAuthority(user, result)) return result;
        TradeExample example = new TradeExample();

        //查询交易,管理员可以查询所有,打手只能看自己的
        example.getOredCriteria().add(example.createCriteria()
                .andGameIdEqualTo(tradeVo.getGameId())
                .andIdEqualTo(tradeVo.getTradeId())
                .andOrderIdEqualTo(tradeVo.getOrderId())
                .andUserIdEqualTo(tradeVo.getUserId())
                .andStatusEqualTo(tradeVo.getTradeStatus())
                .andCreateTimeBetween(tradeVo.getDateMin(), tradeVo.getDateMax()));

        List<Trade> trades = tradeDao.selectByExample(example);
        result.setData(trades);
        return result;
    }

    @Override
    public Result<Trade> revokeTrade(TradeVo tradeVo, User user) {
        Result result = new Result();
        if (Contants.verifyAuthority(user, result)) return result;

        Order order = new Order();
        order.setId(tradeDao.selectByPrimaryKey(tradeVo.getTradeId()).getOrderId());
        order.setType(OrderTypeEnum.WAITING.getCode());
        orderDao.updateByPrimaryKeySelective(order);
        tradeDao.deleteByPrimaryKey(tradeVo.getTradeId());
        return result;
    }

    @Override
    public Result<Map<String, Integer>> countByExample(User user) {
        Result<Map<String, Integer>> result = new Result<>();
        TradeExample example = new TradeExample();
        TradeExample.Criteria criteria = example.createCriteria();
        //是打手
        if (user.getType().equals(UserTypeEnum.BEATER.getCode())) {
            example.getOredCriteria().add(criteria.andUserIdEqualTo(user.getId())
                    .andStatusNotEqualTo(TradeStatusEnum.UNKNOWN.getCode()));
        } else {
            //是管理员或者客服
            example.getOredCriteria().add(criteria.andStatusNotEqualTo(TradeStatusEnum.UNKNOWN.getCode()));
        }
        List<Trade> trades = tradeDao.selectByExample(example);
        if (CollectionUtils.isEmpty(trades)) {
            result.setCode(ErrorEnum.TRADE_NOT_FOUND);
            return result;
        }
        Map<String, Integer> map = new TreeMap<>();
        for (Trade trade : trades) {
            if (map.get(trade.getStatusString()) == null) {
                map.put(trade.getStatusString(), 1);
            } else {
                map.put(trade.getStatusString(), map.get(trade.getStatusString()) + 1);
            }
        }
        result.setData(map);
        return result;
    }

    @Override
    public Result<Object> countMoneyByExample(User user) {
        Result<Object> result = new Result<>();

        if (user.getType().equals(UserTypeEnum.BEATER.getCode())) {
            TradeExample example = new TradeExample();
            example.getOredCriteria().add(example.createCriteria()
                    .andStatusEqualTo(TradeStatusEnum.HAS_BEEN_SETTLED.getCode())
                    .andUserId2EqualTo(user.getId()));
            BigDecimal money = tradeDao.selectMoneyByExample(example);
            if (money == null) {
                money = BigDecimal.ZERO;
            }
            result.setData("累计赚取金额:" + money + "元");
        } else {
            OrderExample example = new OrderExample();
            example.getOredCriteria().add(example.createCriteria()
                    .andTypeEqualTo(OrderTypeEnum.HAS_BEEN_SETTLED.getCode())
                    .andUserIdEqualTo(user.getId()));
            BigDecimal money = orderDao.selectMoneyByExample(example);
            if (money == null) {
                money = BigDecimal.ZERO;
            }
            result.setData("累计发布金额:" + money + "元");
        }
        return result;
    }

    @Override
    public void setExpiredFromEmail() {
        TradeExample example = new TradeExample();
        example.getOredCriteria().add(example.createCriteria().andStatusEqualTo(TradeStatusEnum.IS_WORK.getCode()));
        List<Trade> trades = tradeDao.selectByExample(example);
        for (Trade trade : trades) {
            long checkTime = trade.getCreateTime().getTime() - System.currentTimeMillis();
            //小于3小时
            if (checkTime - 1000 * 60 * 60 * 3 < 0) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            EmailUtils emailUtils = new EmailUtils("", userDao.selectByPrimaryKey(trade.getUserId()).getEmail(), trade.getOrderId().toString());
                            emailUtils.send(7);
                        } finally {
                        }
                    }
                }).start();
                continue;
            }
            //如果小于1天,就发个邮件
            if (checkTime - 1000 * 60 * 60 * 24 < 0) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            EmailUtils emailUtils = new EmailUtils("", userDao.selectByPrimaryKey(trade.getUserId()).getEmail(), trade.getOrderId().toString());
                            emailUtils.send(6);
                        } finally {
                        }
                    }
                }).start();
            }

        }
    }

    @Override
    public Object count() {
        return tradeDao.countByExample(null);
    }

}
